//根据常量value获取常量label

import { invoiceApi } from "/@/api/comprehensive";

/**
 * 获取label值
 */
 export function getLabel<T>(
  str: string | number | undefined | null,
  arr: T[],
  label: string = 'label',
  value: string | number = 'value',
) {
  if (!String(str)) return '';
  const newObj = arr.find((item) => String(item[value]) === String(str));
  const returnValue = newObj?.[label] ?? '';
  return returnValue;
}

//根据常量value获取item项
/**
 * 获取label值
 */
export const getValueItem = <T>(
  str: string | number,
  arr: object[],
  value: string | number = 'value',
): T => {
  if (!String(str)) return null as T;
  const newObj = arr.find((item) => String(item[value]) === String(str));
  const returnValue = newObj ?? null;
  return returnValue as T;
};

// 获取asset文件
export  const getAssetsFile = (url: string) => {
  return new URL(`../../assets/${url}`, import.meta.url).href
}

export const imageSize = (base64Str:string) => {
  if(base64Str.length < 0) return '0';
  return (base64Str.length*0.75).toFixed(2);
}

//接受数据
export  let m_taskPropOption={}
/** 设置缓存 - 建立映射表 */
export const setLocalData=(key)=> {
  // 缓存数据
  localStorage.setItem(`task_${key}_option`, JSON.stringify(m_taskPropOption[key])); // 缓存数据
  localStorage.setItem(`task_${key}_timestamp`, Date.now()); // 记录时间戳
}

export const getLocalData=(key)=> {
  let storageTimestamp = localStorage.getItem(`task_${key}_timestamp`);
  let expires = 1000 * 3600; // 有效时间
  let timestamp = Date.now();  // 当前时间戳
  // 从缓存中取数据（1h内数据）
  if (storageTimestamp && (timestamp - storageTimestamp) < expires) {
    let option :any = localStorage.getItem(`task_${key}_option`); // 从缓存中拿到数据给程序使用
    m_taskPropOption[key] = JSON.parse(option);
    return true;
  }
  return false;
}

// 发票打印需求轮询修改
export const newbillPolling = async (params: any, ids: any[], index: number = 0) => {
  let startIndex = index * 5
  console.log(ids,'ids');
  
  const currentIds = ids.slice(startIndex, startIndex + 5)
  const arrlist = currentIds.toString().split(',')
  console.log(arrlist,'arrlist');
  
    if (arrlist.length === 0 || arrlist[0] === '') return {
    status: true,
    msg: ''
  }
  const data = {
    ...params,
    record_ids: arrlist
  }
  try {
    const res = await invoiceApi(data)  
    if (res.code === 0) {
      index++
      return await newbillPolling(params, ids, index)
    } else {
      return {
        status: false,
        msg: res.msg
      }
    }
  } catch(err) {
    return {
      status: false,
      msg: '',
    }
  }    
}

export const billPolling = async (params: any, ids: any[], index: number = 0) => {
  let startIndex = index * 5
  const currentIds = ids.slice(startIndex, startIndex + 5)
  if (currentIds.length === 0) return {
    status: true,
    msg: ''
  }
  const data = {
    ...params,
    record_ids: currentIds
  }
  try {
    const res = await invoiceApi(data)  
    if (res.code === 0) {
      index++
      return await billPolling(params, ids, index)
    } else {
      return {
        status: false,
        msg: res.msg
      }
    }
  } catch(err) {
    return {
      status: false,
      msg: '',
    }
  }
}


/**
 * @description 轮询调用接口
 * @param { object } params 除了id外的其他参数
 * @param { array } ids id字段组成的数组
 * @param { string } id id字段名
 * @param { function } requestApi 后端接口方法
 * @param { number } amount 每次调用所传id的条数
 * @param { number } index 从第几条开始
 * @return { object } 成功或失败的状态及信息
 */
export const loopRequest = async (requestConfig: any) => {
  let { params, ids, id, requestApi, amount = 5, index = 0 }: {params: any, ids: any[], id: any, requestApi: Function, amount: number, index?: number} = requestConfig;
  let startIndex = index * amount;
  const currentIds = ids.slice(startIndex, startIndex + amount);
  if (currentIds.length === 0) {
    return {
      status: true,
      msg: ''
    };
  }
  const data = {
    ...params,
  };
  data[id] = currentIds;
  try {
    const res = await requestApi(data);
    if (res.code === 0) {
      index++;
      return await loopRequest({
        params, ids, id, requestApi, amount, index
      });
    } else {
      return {
        status: false,
        msg: res.msg,
      }
    }
  } catch(err) {
    return {
      status: false,
      msg: '',
    }
  }
}

/**
 * //非常痛苦加上的备注 2023.08.09
 * @description get回显时upload组件使用上传的附件信息
 * @param { array } data 返回的申请人证件数组
 * @param { string } findStatus 需要返回附件的对应business_file_status
 */
export const getPreviewPic = (data, findStatus) => {
  if (data && data.length) {
    return data.find(item => item.business_file_status === findStatus)?.file_url?.split(',').filter(itemd => itemd).map(item => {
      return {
        url: item,
        delete: true
      }
    })
  }
  return []
}

/**
 * //非常痛苦加上的备注 2023.08.09
 * @description get回显时upload组件使用上传的附件信息--Alone 单个string的意思
 * @param { string } file_url 提供后端返回的附件地址， 一般末尾带逗号的那种（PS：为什么后端返回的时候要多带个逗号？）
 */
export const getPreviewPicAlone = (file_url) => {
  if (!file_url) return []
  return file_url?.split(',').filter(itemd => itemd).map(item => {
    return {
      url: item,
      delete: true
    }
  })
}


